package com.hp.controller;

import com.hp.entity.*;
import com.hp.service.*;
import com.hp.vo.CartVo;
import com.hp.vo.GoodVo;
import com.hp.vo.ItemVo;
import com.hp.vo.OrderVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Author: LiuQiang
 * @Date: 2021/11/2 9:30
 */
@Controller
@RequestMapping("/index")
public class IndexController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodService goodService;
    @Autowired
    private ITypeService typeService;
    @Autowired
    private ICartService cartService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IItemService itemService;

    /**
     * 跳转前端登录页面
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public String login(HttpSession session){
        session.removeAttribute("msg");
        return "index/login";
    }

    /**
     * 验证登录查询信息
     * @param user
     * @param session
     * @param model
     * @return
     */
    @PostMapping("toLogin")
    public String toLogin(User user, HttpSession session, Model model){
        String userName = user.getUserName();
        String passWord = user.getPassWord();
        if (userName.length() >= 2 && userName.length() <= 20 & passWord.length() >=2 && passWord.length() <= 20){
            String reg = "^[A-Za-z0-9]+$";
            if (Pattern.matches(reg,userName) && Pattern.matches(reg,passWord)){
                User findUser = userService.findUserByNameAndPass(user);
                if (null != findUser){
                    //高亮显示”商城首页“
                    model.addAttribute("flag",1);
                    session.setAttribute("user",findUser);
                    //今日推荐6条todayList
                    model.addAttribute("todayList", goodService.findTopsAll());
                    //热销排行前8条hotList
                    model.addAttribute("hotList",goodService.findGoodsBySales());
                    //产品分类前15条dataList包含goodList
                    List<HashMap<String,Object>> dataList = new ArrayList<>();
                    List<Type> typeList = typeService.findTypeAll();
                    for (Type type : typeList){
                        List<Good> goodList = goodService.findGoodAllByTypeId(type.getId());
                        HashMap<String,Object> map = new HashMap<>();
                        map.put("type",type);
                        map.put("goodList",goodList);
                        map.put("listSize",goodList.size());
                        dataList.add(map);
                    }
                    model.addAttribute("dataList",dataList);
                    return "index/index";
                }else {
                    session.setAttribute("msg","登录失败,账号或密码不存在!");
                }
            }else {
                session.setAttribute("msg","登录失败,账号或密码格式不正确!");
            }
        }else {
            session.setAttribute("msg","登录失败,账号或密码长度不正确!");
        }
        return "index/login";
    }

    /**
     * 进入商城首页
     * @param model
     * @return
     */
    @GetMapping("/toIndex")
    public String toIndex(Model model){
        //高亮显示”商城首页“
        model.addAttribute("flag",1);
        //今日推荐6条todayList
        model.addAttribute("todayList", goodService.findTopsAll());
        //热销排行前8条hotList
        model.addAttribute("hotList",goodService.findGoodsBySales());
        //产品分类前15条dataList包含goodList
        List<HashMap<String,Object>> dataList = new ArrayList<>();
        List<Type> typeList = typeService.findTypeAll();
        for (Type type : typeList){
            List<Good> goodList = goodService.findGoodAllByTypeId(type.getId());
            HashMap<String,Object> map = new HashMap<>();
            map.put("type",type);
            map.put("goodList",goodList);
            map.put("listSize",goodList.size());
            dataList.add(map);
        }
        model.addAttribute("dataList",dataList);
        return "index/index";
    }

    /**
     * 清除session，退出登录
     * @param session
     * @return
     */
    @RequestMapping("/userExit")
    public String exit(HttpSession session){
        //清空session中的登录信息
        session.invalidate();//清空session
        //重新访问登录页面(转发，重定向)
        return "index/login";
    }

    /**
     * 跳转我的收获地址页面
     * @return
     */
    @GetMapping("/toAddress")
    public String toAddress(Integer id, Model model,HttpSession session){
        session.removeAttribute("msg");
        User user = userService.findUserById(id);
        model.addAttribute("user",user);
        return "index/my";
    }

    /**
     * 修改姓名、电话、地址
     * @param user
     * @param model
     * @return
     */
    @PostMapping("/myUpdate")
    public String myUpdate(User user, Model model){
        //修改姓名、电话、地址
        userService.userUpdate(user);
        User user1 = userService.findUserById(user.getId());
        model.addAttribute("user",user1);
        model.addAttribute("msg","保存成功");
        return "index/my";
    }

    /**
     * 进入今日推荐页面
     * @param model
     * @return
     */
    @GetMapping("/toToday")
    public String toToday(Model model){
        //高亮显示”今日推荐“
        model.addAttribute("flag",2);
        //今日推荐6条goodList
        model.addAttribute("goodList", goodService.findTopsAll());
        return "index/goods";
    }

    /**
     * 进入热销排行
     * @param model
     * @return
     */
    @GetMapping("/toHot")
    public String toHot(Model model){
        //高亮显示”热销排行“
        model.addAttribute("flag",3);
        //热销排行
        model.addAttribute("goodList",goodService.findGoodsBySalesAll());
        return "index/goods";
    }

    /**
     * 进入新品上市
     * @param model
     * @return
     */
    @GetMapping("/toNew")
    public String toNew(Model model){
        //高亮显示”新品上市“
        model.addAttribute("flag",4);
        //新品上市
        model.addAttribute("goodList",goodService.findGoodsBySalesNew());
        return "index/goods";
    }

    /**
     * 根据name模糊查询
     * @param name
     * @param model
     * @return
     */
    @PostMapping("/search")
    public String search(String name,Model model){
        //根据name模糊查询
        model.addAttribute("goodList",goodService.findGoodsByNameLike(name));
        //输入框依旧显示name
        model.addAttribute("search",name);
        return "index/goods";
    }

    /**
     * 商品详情
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public String detail(Integer id, Model model){
        if (id != null && id != 0){
            //根据id查询goods表的信息
            Good good = goodService.findGoodById(id);
            GoodVo goodVo = new GoodVo();
            //vo视图赋值
            BeanUtils.copyProperties(good,goodVo);
            //根据goods表的type_id查询types表的信息
            goodVo.setType(typeService.findTypeById(good.getTypeId()));
            model.addAttribute("good",goodVo);
            model.addAttribute("todayList", goodService.findTopsAll());
            return "index/detail";
        }else {
            return "index/error";
        }
    }

    /**
     * 更多推荐
     * @param model
     * @return
     */
    @GetMapping("/today")
    public String today(Model model){
        model.addAttribute("goodList",goodService.findTopsAllToday());
        return "index/goods";
    }

    /**
     * 更多热销
     * @param model
     * @return
     */
    @GetMapping("/hot")
    public String hot(Model model){
        model.addAttribute("goodList",goodService.findGoodsBySalesAll());
        return "index/goods";
    }

    /**
     * 查看更多
     * @param typeId
     * @param model
     * @return
     */
    @GetMapping("/type")
    public String type(Integer typeId, Model model){
         model.addAttribute("goodList",goodService.findGoodsByTypeId(typeId));
         model.addAttribute("type",typeService.findTypeById(typeId));
        return "index/goods";
    }

    /**
     * 进入注册页面
     * @return
     */
    @GetMapping("/register")
    public String register(){
        return "index/register";
    }

    /**
     * 注册账号
     * @param user
     * @param model
     * @return
     */
    @PostMapping("/reg")
    public String reg(User user, Model model){
        //注册成功跳转登录，失败原页面
        int result = userService.userReg(user);
        if (result >=1){
            return "redirect:/index/login";
        }else {
            //可判断注册的用户名有无重复
            model.addAttribute("msg","注册失败!");
            return "/index/register";
        }
    }

    /**
     * 加入购物车
     * @param goodId
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/addcart")
    public String addcart(Integer goodId, HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if (user == null){
            return "redirect:/index/login";
        }else {
             List<CartVo> cartVoList = cartService.addCart(goodId,session);
             model.addAttribute("cartList",cartVoList);
             int cartTotal = 0;
             for (CartVo cartVo : cartVoList){
                 cartTotal += cartVo.getTotal();
             }
             model.addAttribute("cartTotal",cartTotal);
        }
        return "/index/cart";
    }

    /**
     * 点击我的购物车
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/toCart")
    public String toCart(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if (user == null){
            return "redirect:/index/login";
        }else {
            List<CartVo> cartVoList = cartService.addCart(0,session);
            if (cartVoList != null){
                model.addAttribute("cartList",cartVoList);
                int cartTotal = 0;
                for (CartVo cartVo : cartVoList){
                    cartTotal += cartVo.getTotal();
                }
                model.addAttribute("cartTotal",cartTotal);
                return "/index/cart";
            }else {
                model.addAttribute("cartList",null);
                return "/index/cart";
            }
        }

    }

    /**
     * 购物车商品数量的增加减
     * @param subtract
     * @param add
     * @param id
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/updateCartsAmount")
    public String updateCartsAmount(Integer subtract,Integer add,Integer id,HttpSession session,Model model){
        cartService.updateCartsByAmountSubtractAndAdd(subtract,add,id);
        List<CartVo> cartVoList = cartService.addCart(0,session);
        model.addAttribute("cartList",cartVoList);
        int cartTotal = 0;
        for (CartVo cartVo : cartVoList){
            cartTotal += cartVo.getTotal();
        }
        model.addAttribute("cartTotal",cartTotal);
        return "/index/cart";
    }

    /**
     * 我的订单
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/order")
    public String order(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if (user != null){
            model.addAttribute("orderList",orderService.findIndexOrderAll(user.getId()));
            return "/index/order";
        }
        return "redirect:/index/login";
    }

    /**
     * 进入修改密码
     * @return
     */
    @GetMapping("/password")
    public String password(HttpSession session){
        session.removeAttribute("msg");
        return "/index/password";
    }

    /**
     * 修改密码
     * @param user
     * @param model
     * @return
     */
    @PostMapping("/passwordUpdate")
    public String passwordUpdate(User user, Model model){
        userService.userReset(user);
        model.addAttribute("msg","保存成功");
        return "/index/password";
    }

    /**
     * 删除购物车商品信息
     * @param id
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/cartDelete")
    public String cartDelete(Integer id,HttpSession session,Model model){
        cartService.deleteCartById(id);
        User user = (User) session.getAttribute("user");
        if (user == null){
            return "redirect:/index/login";
        }else {
            List<CartVo> cartVoList = cartService.addCart(0,session);
            model.addAttribute("cartList",cartVoList);
            int cartTotal = 0;
            for (CartVo cartVo : cartVoList){
                cartTotal += cartVo.getTotal();
            }
            model.addAttribute("cartTotal",cartTotal);
        }
        return "/index/cart";
    }

    /**
     * 购物车中的立即结算
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/orderSave")
    public String orderSave(HttpSession session,Model model){
        User user = (User) session.getAttribute("user");
        //根据user_id查询购物车信息
        List<CartVo> cartVoList = cartService.addCart(0,session);
        int cartTotal = 0;
        int cartAmount = 0;
        for (CartVo cartVo : cartVoList){
            cartTotal += cartVo.getTotal();
            cartAmount += cartVo.getAmount();
        }
        //赋值
        Order order = new Order();
        order.setTotal(cartTotal);
        order.setAmount(cartAmount);
        order.setStatus(1);
        order.setPayType(1);
        order.setName(user.getName());
        order.setPhone(user.getPhone());
        order.setAddress(user.getAddress());
        order.setUserId(user.getId());
        //新增订单信息
        orderService.orderSave(order);
        //得到自增后的id
        Integer orderId = order.getId();

        //新增订单详情
        for (CartVo cartVo : cartVoList){
            Item item1 = new Item();
            item1.setPrice(cartVo.getAmount() * cartVo.getGood().getPrice());
            item1.setAmount(cartVo.getAmount());
            item1.setOrderId(orderId);
            item1.setGoodId(cartVo.getGoodId());
            itemService.insertItem(item1);
        }

        //根据order_id查询items表的信息List<Item>
        List<Item> itemList = itemService.findItemByOrderId(orderId);
        List<ItemVo> itemVoList = new ArrayList<>();
        for (Item item : itemList){
            ItemVo itemVo = new ItemVo();
            BeanUtils.copyProperties(item,itemVo);
            //根据itemList的good_id查询goods表的商品信息
            Good good = goodService.findGoodsByGoodId(item.getGoodId());
            itemVo.setGood(good);
            itemVoList.add(itemVo);
        }
        OrderVo orderVo = new OrderVo();
        BeanUtils.copyProperties(order,orderVo);
        orderVo.setItemVo(itemVoList);
        model.addAttribute("order",orderVo);

        //删除购物车中的商品信息，根据user_id删除购物车商品信息
        cartService.deleteCartByUserId(user.getId());
        return "/index/pay";
    }

    /**
     * 订单页面中的确认支付
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/orderPay")
    public String orderPay(Integer id, Model model){
        //根据id查询orders表的商品信息order
        Order order = orderService.findOrdersAllById(id);
        //根据order_id查询items表的信息List<Item>
        List<Item> itemList = itemService.findItemByOrderId(order.getId());
        List<ItemVo> itemVoList = new ArrayList<>();
        for (Item item : itemList){
            ItemVo itemVo = new ItemVo();
            BeanUtils.copyProperties(item,itemVo);
            //根据itemList的good_id查询goods表的商品信息
            Good good = goodService.findGoodsByGoodId(item.getGoodId());
            itemVo.setGood(good);
            itemVoList.add(itemVo);
        }
        OrderVo orderVo = new OrderVo();
        BeanUtils.copyProperties(order,orderVo);
        orderVo.setItemVo(itemVoList);
        model.addAttribute("order",orderVo);
        return "/index/pay";
    }

    /**
     * 支付成功
     * @param order
     * @return
     */
    @PostMapping("/orderPay")
    public String orderPay(Order order){
        int result = orderService.orderPay(order);
        if (result > 0){
            return "/index/payok";
        }
        return "/index/error";
    }
}
